"""
在线词典 ： 服务端逻辑处理
"""
from socket import *
from multiprocessing import Process
from dict_db import *

class Handle(Process):
    def __init__(self,conn,addr):
        self.db=DictData()
        self.conn=conn
        self.addr=addr
        self.user_id=0
        super().__init__()

    def run(self):
        while True:
            request=self.conn.recv(128)
            tmp=request.decode().split("\t")
            if not request or request==b"E":
                break
            elif tmp[0]=="R":
                self.do_sign(tmp[1],tmp[2])
            elif tmp[0]=="L":
                self.do_login(tmp[1],tmp[2])
            elif tmp[0]=="Q":
                self.do_query(tmp[1])
            elif tmp[0]=="H":
                self.do_hist()
        self.db.close()
        self.conn.close()

    def do_sign(self,name,passwd):
        if self.db.sign(name,passwd):
            self.conn.send(b"T")
        else:
            self.conn.send(b"F")

    def do_login(self,name,passwd):
        res=self.db.login(name,passwd)
        if res:
            self.conn.send(b"T")
            self.user_id=res[0]
        else:
            self.conn.send(b"F")

    def do_query(self,word):
        data=self.db.query(word)
        if data:
            res="T\t"+data[1]
            self.conn.send(res.encode())
            self.db.insert_hist(self.user_id,data[0])
        else:
            self.conn.send(b"F")

    def do_hist(self):
        data=self.db.hist(self.user_id)
        if data:
            res="T\t"
            for row in data:
                res += "%s,%s,%s;" % row
            self.conn.send(res.encode())
        else:
            self.conn.send(b"F")

class DictServe:
    def __init__(self, host="", port=0):
        self.host = host
        self.port = port
        self.address = (host, port)
        self.sock = self._create_socket()

    def _create_socket(self):
        tcp_sock=socket()
        tcp_sock.bind(self.address)
        return tcp_sock

    def serve_forever(self):
        self.sock.listen(5)
        print("Listen the port %d" % self.port)
        while True:
            conn,addr=self.sock.accept()
            print("Connect from",addr)
            p=Handle(conn,addr)
            p.start()


if __name__=='__main__':
    dict=DictServe(host='0.0.0.0',port=8888)
    dict.serve_forever()
